/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radiostation;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import model.MusicGroup;
import model.DBManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.Album;
import model.Artist;

/**
 *
 * @author sky
 */


public class GroupJFrame extends javax.swing.JFrame {

    /**
     * Creates new form GroupJFrame
     */
    private MenuJFrame parent;
    
    public GroupJFrame() {
        
        em = DBManager.em;
        if(!em.getTransaction().isActive())
        {
            em.getTransaction().begin();
        }
        initComponents();
    }
    
    public GroupJFrame(MenuJFrame parent) {
        
        this.parent = parent;
        em = DBManager.em;
        if(!em.getTransaction().isActive())
        {
            em.getTransaction().begin();
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        groupQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("Select mg from MusicGroup mg");
        groupQueryList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(groupQuery.getResultList());
        headerPanel = new javax.swing.JPanel();
        headerLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        groupTable = new javax.swing.JTable();
        actionPanel = new javax.swing.JPanel();
        insertButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        alterButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Πίνακας Συγκροτημάτων");

        headerPanel.setBackground(new java.awt.Color(255, 204, 0));
        headerPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        headerLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        headerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        headerLabel.setText("Πίνακας Συγκροτημάτων");

        javax.swing.GroupLayout headerPanelLayout = new javax.swing.GroupLayout(headerPanel);
        headerPanel.setLayout(headerPanelLayout);
        headerPanelLayout.setHorizontalGroup(
            headerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(headerPanelLayout.createSequentialGroup()
                .addGap(301, 301, 301)
                .addComponent(headerLabel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        headerPanelLayout.setVerticalGroup(
            headerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(headerPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(headerLabel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        groupTable.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, groupQueryList, groupTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${musicGroupName}"));
        columnBinding.setColumnName("Επωνυμία Συγκροτήματος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${musicGroupFormdate}"));
        columnBinding.setColumnName("Ημερομηνία Δημιουργίας");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(groupTable);

        actionPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Επιλογή Ενέργειας"));

        insertButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        insertButton.setText("Εισαγωγή");
        insertButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insertButtonActionPerformed(evt);
            }
        });

        deleteButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        deleteButton.setText("Διαγραφή");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        alterButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        alterButton.setText("Μεταβολή");
        alterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alterButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout actionPanelLayout = new javax.swing.GroupLayout(actionPanel);
        actionPanel.setLayout(actionPanelLayout);
        actionPanelLayout.setHorizontalGroup(
            actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(actionPanelLayout.createSequentialGroup()
                .addComponent(insertButton, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(alterButton, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                .addContainerGap())
        );
        actionPanelLayout.setVerticalGroup(
            actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(actionPanelLayout.createSequentialGroup()
                .addContainerGap(26, Short.MAX_VALUE)
                .addGroup(actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(insertButton)
                    .addComponent(deleteButton)
                    .addComponent(alterButton)))
        );

        exitButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        exitButton.setText("Επιστροφή στο Μενού");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(headerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(actionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE)
                        .addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(headerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(actionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(exitButton)
                        .addGap(10, 10, 10)))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        // TODO add your handling code here:
        parent.setEnabled(true);
        dispose();
    }//GEN-LAST:event_exitButtonActionPerformed

    private void insertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertButtonActionPerformed
        // TODO add your handling code here:
        musicgroup = new MusicGroup();
        
        
        EditGroupFrame editgroupframe = new EditGroupFrame(musicgroup);
        editgroupframe.setVisible(true);
        
        thisFrame = this;
        thisFrame.setEnabled(false);
        editgroupframe.addWindowListener(new WindowListener(){
            
            public void windowClosed(WindowEvent arg0)
            {
                
                System.out.println("Window closed.");
                if(MyWindowEvent.isExitAndSave(arg0))
                {
                    em.persist(musicgroup);
                    groupQueryList.add(musicgroup);
                    em.getTransaction().commit();
                    em.getTransaction().begin();
                    
                    int row =groupQueryList.size()-1;
                    groupTable.setRowSelectionInterval(row, row);
                    groupTable.scrollRectToVisible(groupTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                }
                else
                {
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = groupQuery.getResultList();
                    for (Object entity : data)
                    {
                        em.refresh(entity);
                        
                    }
                   groupQueryList.clear();
                    groupQueryList.addAll(data);
                }
                
            }
            
            public void windowActivated(WindowEvent arg0)
            {
                
                System.out.println("Window activated.");
            }
            
            public void windowClosing(WindowEvent arg0)
            {
                
                System.out.println("Window closing.");
            }
            
            public void windowDeactivated(WindowEvent arg0)
            {
                
                System.out.println("Window deactivated.");
            }
            
            public void windowDeiconified(WindowEvent arg0)
            {
                
                System.out.println("Window deiconified.");
            }
            
            public void windowIconified(WindowEvent arg0)
            {
                
                System.out.println("Window iconified.");
            }
            
            public void windowOpened(WindowEvent arg0)
            {
                
                System.out.println("Window opened.");
            }
        });
        
    }//GEN-LAST:event_insertButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        // TODO add your handling code here:
        s=groupTable.getSelectedRow();
        if(s<0)
        {
            JOptionPane.showMessageDialog(new JFrame(), "Επιλέξτε ένα συγκρότημα από τον πίνακα προς διαγραφή");
             
        }
        else
        {
            musicgroup = groupQueryList.get(groupTable.convertRowIndexToModel(s));
            
            for(Artist art:musicgroup.getArtistList())
                    {
                        art.setArtistMusicGroupId(null);
                        em.merge(art);
                        em.getTransaction().commit();
                        em.getTransaction().begin();
                    }
            for(Album album:musicgroup.getAlbumList())
                    {
                        album.setAlbumMusicGroupId(null);
                        em.merge(album);
                        em.getTransaction().commit();
                        em.getTransaction().begin();
                        em.remove(album);
                        em.getTransaction().commit();
                        em.getTransaction().begin();
                    }
            
            groupQueryList.remove(musicgroup);
            em.remove(musicgroup);
            em.getTransaction().commit();
            em.getTransaction().begin();
            
        }
              
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void alterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alterButtonActionPerformed
        // TODO add your handling code here:
        
        s = groupTable.getSelectedRow();
        if(s<0)
        {
            JOptionPane.showMessageDialog(new JFrame(), "Επέλεξε ένα συγκρότημα από τον πίνακα");
            return;
        }
        musicgroup = groupQueryList.get(s);
        
        EditGroupFrame egf = new EditGroupFrame(musicgroup);
        egf.setVisible(true);
        
        thisFrame = this;
        thisFrame.setEnabled(false);
        egf.addWindowListener(new WindowListener(){
            
            public void windowClosed(WindowEvent arg0)
            {
                
                System.out.println("Window closed.");
                if(MyWindowEvent.isExitAndSave(arg0))
                {
                    
                    em.merge(musicgroup);
                    em.getTransaction().commit();
                    em.getTransaction().begin();
                    groupQueryList.set(s,musicgroup);
                    groupTable.setRowSelectionInterval(s, s);
                    groupTable.scrollRectToVisible(groupTable.getCellRect(s, 0, true));
                    thisFrame.setEnabled(true);
                    
                }
                else
                {
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = groupQuery.getResultList();
                    for (Object entity : data)
                    {
                        em.refresh(entity);
                        
                    }
                    groupQueryList.clear();
                    groupQueryList.addAll(data);
                }
                
            }
            
            public void windowActivated(WindowEvent arg0)
            {
                
                System.out.println("Window activated.");
            }
            
            public void windowClosing(WindowEvent arg0)
            {
                
                System.out.println("Window closing.");
            }
            
            public void windowDeactivated(WindowEvent arg0)
            {
                
                System.out.println("Window deactivated.");
            }
            
            public void windowDeiconified(WindowEvent arg0)
            {
                
                System.out.println("Window deiconified.");
            }
            
            public void windowIconified(WindowEvent arg0)
            {
                
                System.out.println("Window iconified.");
            }
            
            public void windowOpened(WindowEvent arg0)
            {
                
                System.out.println("Window opened.");
            }
        });
    }//GEN-LAST:event_alterButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GroupJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GroupJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GroupJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GroupJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GroupJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel actionPanel;
    private javax.swing.JButton alterButton;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton exitButton;
    private javax.persistence.Query groupQuery;
    private java.util.List<MusicGroup> groupQueryList;
    private javax.swing.JTable groupTable;
    private javax.swing.JLabel headerLabel;
    private javax.swing.JPanel headerPanel;
    private javax.swing.JButton insertButton;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    MusicGroup musicgroup;
    EntityManager em;
    JFrame thisFrame;
    int s;
    
    
}
